//
//  PopAnimator.m
//  UIViewControllerTransitionDemo
//
//  Created by Guo Rui on 2017/7/4.
//  Copyright © 2017年 GR Harry. All rights reserved.
//

#import "PopAnimator.h"
#import "PushViewController.h"
#import "SceneryCell.h"
#import "SceneryDetailViewController.h"

@implementation PopAnimator

- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext {
    return .8f;
}

- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext {
    SceneryDetailViewController *fromVc = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    PushViewController *toVc = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    UIView *containerView = [transitionContext containerView];
    
    // 1. 获取fromVc的detailImageView副本，和位置
    UIView *snapView = [fromVc.detailImageView snapshotViewAfterScreenUpdates:NO];
    snapView.frame = [containerView convertRect:fromVc.detailImageView.frame fromView:fromVc.detailImageView.superview];
    fromVc.detailImageView.hidden = YES;
    
    // 2. 获取toVc的cell中imageView的位置
    SceneryCell *cell = [toVc cellForSelected];
    CGRect snapFinalRect = [containerView convertRect:cell.pictureImageView.frame fromView:cell.pictureImageView.superview];
    cell.pictureImageView.hidden = YES;
    toVc.view.alpha = 0.f;
    
    [containerView addSubview:toVc.view];
    [containerView addSubview:snapView];
    
    // 3. 动画
    [UIView animateWithDuration:[self transitionDuration:transitionContext]
                          delay:0
         usingSpringWithDamping:.5
          initialSpringVelocity:.8
                        options:UIViewAnimationOptionCurveLinear
                     animations:^{
                         snapView.frame = snapFinalRect;
                         toVc.view.alpha = 1.f;
                     } completion:^(BOOL finished) {
                         [snapView removeFromSuperview];
                         
                         if (![transitionContext transitionWasCancelled]) {
                             cell.pictureImageView.hidden = NO;
                         }
                         else {
                             fromVc.detailImageView.hidden = NO;
                         }
                         [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
                     }];
}

@end
